import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/common/dialogs/del_dialog.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/bank_card_list_vo.dart';
import 'package:xinxuan/vo/common_vo/common_bank_card_item_vo.dart';
import 'package:xinxuan/vo/system_bank_list_vo.dart';
import 'package:xinxuan/vo/verification_vo.dart';

class BankCardController extends GetxController {

  final CommonPageController commonPageController = Get.find();
  
  /// 抢购银行卡
  var purchaseBankArr = <CommonBankCardItemVo>[].obs;
  /// 提现银行卡
  var withdrawalBankArr = <CommonBankCardItemVo>[].obs;
  /// 姓名
  var accountName = ''.obs;
  /// 账号
  var cardNumber = ''.obs;
  /// 是否默认 0 否， 1 是
  var isDefault = 1.obs;
  /// 银行卡ID
  var bankId = 0.obs;
  /// 开户行
  var subbranch = '';
  /// 验证码
  var verificationCode = ''.obs;
  /// 系统银行卡列表
  var systemBankArr = <SystemBankItem>[].obs;
  /// 银行卡下拉选中项
  var scrollController = FixedExtentScrollController( initialItem: 0).obs;
  /// 选中的银行卡项
  var selectedBankItem = SystemBankItem().obs;
  /// 卡片用途
  var type = 1.obs;
  /// 身份证号码
  var identityNumber = ''.obs;
  /// 银行卡ID （修改时使用）
  int id = 0;
  // /// 倒计时剩余时间
  var duration = 60.obs;
  /// 时间倒计时
  Timer? _timer;  
  String verificationKey = '';

  // /// 是否存在抢购银行卡
  // var isPurchaseExist = 0.obs;
  // /// 是否存在提现银行卡
  // var isWithdrawalExist = 0.obs;
  // List<Map<String, dynamic>> typeList = [
  //   {
  //     'type': 1,
  //     'label': '抢购'
  //   },
  //   {
  //     'type': 2,
  //     'label': '提现'
  //   }
  // ];

  // /// 可用类型
  // List<Map<String, dynamic>> availableTypeList = [];

  @override
  void onReady() {
    getBankCardList();
    // getSystemBankList();
    super.onReady();
  }

  /// 获取系统银行卡列表
  Future<List<SystemBankItem>> getSystemBankList() async {
    SystemBankListVo systemBankListVo = await HttpUtilService.getSystemBankList(type: type.value);
    systemBankArr.value = systemBankListVo.data!;
    return systemBankListVo.data!;
  }
  
  /// 获取银行卡列表
  getBankCardList() async {
    BankCardListVo bankCardListVo = await HttpUtilService.getBankCardList();
    purchaseBankArr.value = [];
    withdrawalBankArr.value = [];
    bankCardListVo.data!.forEach((item) {
      if (item.type == 1) {
        purchaseBankArr.add(item);
      } else if (item.type == 2) {
        withdrawalBankArr.add(item);
      }
    });
    update();
  }

  /// 初始化数据
  ininAddBank(int bankType) async {
    accountName.value = '';
    cardNumber.value = '';
    isDefault.value = 1;
    bankId.value = 0;
    verificationCode.value = '';
    scrollController.value = FixedExtentScrollController( initialItem: 0);
    identityNumber.value = '';
    subbranch = '';
    type.value = bankType;
    selectedBankItem.value = SystemBankItem();
    // initTypeList();
    await getSystemBankList();
    update();
  }

  /// 初始化修改数据
  ininEditBank(Map<String, dynamic> map, int bankType) async {
    id = map['id'];
    accountName.value = map['accountName'];
    cardNumber.value = map['cardNumber'];
    isDefault.value = map['isDefault'];
    bankId.value = map['bankId'];
    type.value = bankType;
    identityNumber.value = map['identityNumber'];
    verificationCode.value = '';
    subbranch = map['subbranch'];
    await getSystemBankList();
    if (systemBankArr.length > 0) {
      for (int i = 0; i < systemBankArr.length; i++) {
        if (bankId.value == systemBankArr[i].id) {
          scrollController.value = FixedExtentScrollController( initialItem: i);
          selectedBankItem.value = systemBankArr[i];
          break;
        }
      }
    } else {
      scrollController.value = FixedExtentScrollController( initialItem: 0);
      selectedBankItem.value = SystemBankItem();
    }
    // initTypeList(initType: type.value);
    update();
  }

  /// 添加银行卡
  addBankCard() async {
    if (TextUtil.isEmpty(accountName.value)) {
      EasyLoading.showToast('请填写账号名');
      return;
    }
    if (TextUtil.isEmpty(cardNumber.value)) {
      EasyLoading.showToast('请填写账号');
      return;
    }
    if (bankId.value <= 0) {
      EasyLoading.showToast('请选择所属银行');
      return;
    }
    // if (TextUtil.isEmpty(subbranch.value)) {
    //   EasyLoading.showToast('请填写开户行');
    //   return;
    // }
    if (TextUtil.isEmpty(verificationCode.value)) {
      EasyLoading.showToast('请填写验证码');
      return;
    }
    if (!RegexUtil.isIDCard18(identityNumber.value)) {
      EasyLoading.showToast('请填写正确身份证号');
      return;
    }
    if (bankId.value != 1 && bankId.value != 2 && TextUtil.isEmpty(subbranch)) {
      EasyLoading.showToast('请填写开户支行');
      return;
    }
    await HttpUtilService.addBankCard(
      accountName: accountName.value, 
      cardNumber: cardNumber.value, 
      isDefault: isDefault.value, 
      bankId: bankId.value, 
      verificationCode: verificationCode.value,
      identityNumber: identityNumber.value,
      type: type.value,
      verificationKey: verificationKey,
      subbranch: subbranch
    );
    Get.back();
    EasyLoading.showToast('添加成功');
    getBankCardList();
  }

  /// 修改选中银行卡
  changeBankIndex(int index) {
    scrollController.value = FixedExtentScrollController( initialItem: index);
  }

  /// 确定选中银行卡
  determineBank() {
    selectedBankItem.value = systemBankArr[scrollController.value.initialItem];
    bankId.value = selectedBankItem.value.id!;
    update();
  }

  /// 修改银行卡信息
  editBankCard() async {
    if (TextUtil.isEmpty(accountName.value)) {
      EasyLoading.showToast('请填写账号名');
      return;
    }
    if (TextUtil.isEmpty(cardNumber.value)) {
      EasyLoading.showToast('请填写账号');
      return;
    }
    if (bankId.value <= 0) {
      EasyLoading.showToast('请选择所属银行');
      return;
    }
    // if (TextUtil.isEmpty(subbranch.value)) {
    //   EasyLoading.showToast('请填写开户行');
    //   return;
    // }
    if (TextUtil.isEmpty(verificationCode.value)) {
      EasyLoading.showToast('请填写验证码');
      return;
    }
    if (bankId.value != 1 && bankId.value != 2 && TextUtil.isEmpty(subbranch)) {
      EasyLoading.showToast('请填写开户支行');
      return;
    }
    bool res = await HttpUtilService.editBankCard(
      id: id,
      accountName: accountName.value, 
      cardNumber: cardNumber.value, 
      isDefault: isDefault.value, 
      bankId: bankId.value, 
      verificationCode: verificationCode.value,
      identityNumber: identityNumber.value,
      type: type.value,
      verificationKey: verificationKey,
      subbranch: subbranch
    );
    if (res) {
      Get.back();
      EasyLoading.showToast('修改成功');
      getBankCardList();
    }
  }

  /// 删除银行卡
  delBankCard() async {
    Get.dialog(DelDialog(message: '确定删除此银行卡吗？', onTap: () async {
      bool res = await HttpUtilService.delBankCard(id: id);
      if (res) {
        Get.back();
        EasyLoading.showToast('删除成功');
        getBankCardList();
      }
    }));
  }

  /// 获取验证码
  getSmsCode() async {
    VerificationVo? res = await HttpUtilService.getVerificationCode(mobile: commonPageController.userData.value.mobile!, type: 'bank');
    if (res != null) {
      verificationKey = res.data!.verificationKey!;
      EasyLoading.showToast('发送成功');
      _timer?.cancel();
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        duration.value--;
        if (duration.value == 0) {
          _timer?.cancel();
          duration.value = 60;
        }
      });
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }


}